package com.tang.sharding.schedule.task.hook;

import com.tang.sharding.schedule.task.jdbc.AbstractJdbcRunnableTask;
import com.tang.sharding.schedule.task.manager.AbstractTaskManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author Tang
 * @classname CronTaskShutdownHook
 * @description [ CronTask Hook ]
 * @date 2021/8/5 16:57
 */
@Slf4j
public class CronTaskShutdownHook extends AbstractTaskShutdownHook {

    public CronTaskShutdownHook(AbstractTaskManager abstractTaskManager) {
        super(abstractTaskManager);
    }

    @Override
    protected void taskShutdownWork() {
        // 任务结果
        Map<String, ScheduledTask> scheduledTaskMap = abstractTaskManager.getScheduledTaskMap();
        // 注册器
        ScheduledTaskRegistrar scheduledTaskRegistrar = this.abstractTaskManager.getScheduledTaskRegistrar();
        List<CronTask> cronTaskList = scheduledTaskRegistrar.getCronTaskList();
        // 取消任务
        cronTaskList.forEach(cronTask -> {
            Optional.ofNullable(cronTask.getRunnable())
                    .filter(item -> item instanceof AbstractJdbcRunnableTask)
                    .map(item -> (AbstractJdbcRunnableTask)item)
                    .ifPresent(item -> {
                        String taskId = item.getTaskId();
                        abstractTaskManager.cancelTask(taskId);
                        log.info("正在销毁任务id:[{}],表名:[{}]的后台任务...", taskId,item.getTableRule().getLogicTable());
                    });
        });
    }
}